package com.yyge.common.util;

import cn.hutool.core.util.NumberUtil;
import com.yyge.common.enums.AckCode;
import com.yyge.common.exception.ServiceException;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 最原始的servlet工具类
 * @author Administrator
 */
public class ServletUtils {

    /**
     * 得到HttpServletRequest对象
     * @return
     */
    public static HttpServletRequest getRequest(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) requestAttributes;
        return servletRequestAttributes.getRequest();
    }


    /**
     * 根据键获取请求中的值
     * @param key
     * @return
     */
    public static String getParams(String key){
        return getRequest().getParameter(key);
    }

    /**
     *  得到参数把变整数
     * @param key
     * @return
     */
    public static Integer getParamsToInt(String key){
        String value=getParams(key);
        if(NumberUtil.isInteger(value)){
           return  Integer.parseInt(value);
        }
        else{
            throw new ServiceException(AckCode.SYSTEM_PARAM_FAIL);
        }
    }

    /**
     * 得到参数把变整数
     * @param key
     * @param defaultValue  默认值
     * @return
     */
    public static Integer getParamsToInt(String key,int defaultValue){
        String value=getParams(key);
        if(NumberUtil.isInteger(value)){
            return  Integer.parseInt(value);
        }
        else{
           return defaultValue;
        }
    }


}
